
#include "page_com.h"

static uint8_t page_now = 0;
static uint8_t page_old = 0;

//-------------------------------------------------------------
void page_manager_init(int ptime) {
  ptime = ptime;
}

//------------------------------------------------------------
bool page_manager_reg(uint8_t page_id,
                      PageCallbackNew load_cb,
                      PageCallbackFun loop_cb,
                      PageCallbackFun exit_cb,
                      PageCallbackEnt event_cb) {
  if (page_id > PAGE_MAX) return false;
  page_list[page_id].load_cb = load_cb;
  page_list[page_id].loop_cb = loop_cb;
  page_list[page_id].exit_cb = exit_cb;
  page_list[page_id].event_cb = event_cb;
  page_list[page_id].docker = load_cb();
  return true;
}

//-------------------------------------------------------------
void page_manager_event(int key) {
  if (page_list[page_now].event_cb != NULL)
    page_list[page_now].event_cb(key);
}

//-------------------------------------------------------------
void page_manager_switch(uint8_t page_id) {
  if (page_id > PAGE_MAX) return;
  page_old = page_now;
  page_now = page_id;
}

//=============================================================
static void anim_x_cb(void * var, int32_t v)
{
  lv_obj_set_x((_lv_obj_t*)var, v);
}
//-------------------------------------------------------------
void page_user_anim(lv_obj_t *docker,
                    int32_t start, int32_t end,
                    lv_anim_path_cb_t path_cb) {
  lv_anim_t a;
  lv_anim_init(&a);
  lv_anim_set_var(&a, docker);
  lv_anim_set_values(&a, start, end);
  lv_anim_set_time(&a, 300);
  lv_anim_set_exec_cb(&a, anim_x_cb);
  lv_anim_set_path_cb(&a, path_cb);
  lv_anim_start(&a);
}
//-------------------------------------------------------------
void page_manager_loop() {
  if (page_now != page_old) {
    //---------------------------------------------
    if (page_list[page_old].exit_cb != NULL)
      page_list[page_old].exit_cb(page_list[page_old].docker);
    page_user_anim(page_list[page_old].docker, 0, 280, PAGE_ANIM);
    lv_obj_add_flag(page_list[page_old].docker, LV_OBJ_FLAG_HIDDEN);
    //---------------------------------------------
    if (page_list[page_now].loop_cb != NULL)
      page_list[page_now].loop_cb(page_list[page_now].docker);
    page_user_anim(page_list[page_now].docker, -280, 0, PAGE_ANIM);
    lv_obj_clear_flag(page_list[page_now].docker, LV_OBJ_FLAG_HIDDEN);
    page_old = page_now;
  } else {
    //page_list[page_now].loop_cb(page_list[page_now].docker);
    page_now = page_now;
  }
}
